package com.syyc.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.syyc.pojo.Content;
import com.syyc.service.MysqlService;
import com.syyc.service.impl.MysqlServiceImpl;
import com.syyc.utils.ExcelUtil2;
import com.syyc.utils.MyBatisUtils;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;

import java.io.*;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * @author huimin
 * @date 2021/10/29
 * @apiNote
 */
@SuppressWarnings("all")
public class MysqlAppController {

    private static MysqlService mysqlService = new MysqlServiceImpl();

    public static void main(String[] args) throws IOException {
        outputToExcel();
    }

    /**
     * 读取Mysql中的数据输出到Excel
     */
    public static void outputToExcel() throws IOException {

        // excel标题
        String[] title = {"视频名称", "封面地址", "视频地址", "类型", "集数"};

        // excel文件名
        String fileName = "bilibili热播动漫信息表.xls";

        // sheet名
        String sheetName = "B站热播动漫";

        File dir = new File("g://excel/");

        if (!dir.exists()) {
            dir.mkdirs();
        }

        fileName = dir + File.separator + fileName;

        BufferedOutputStream bw = new BufferedOutputStream(new FileOutputStream(fileName));

        List<Content> contentList = mysqlService.selectAllVideoList();

        HSSFWorkbook workbook = ExcelUtil2.getHSSFWorkbook(sheetName, title, contentList, null);

        workbook.write(bw);

        // 关闭流
        bw.close();

    }

    /**
     * 爬取视频
     */
    public static void crawlVideo(){
        int imageNum = 1;//统计图片数量
        int pageSize = 172;//总页数
        for (int page = 1; page <= pageSize; page++) {

            String url = "https://api.bilibili.com/pgc/season/index/result?season_version=-1&area=-1&is_finish=-1&copyright=-1&season_status=-1&season_month=-1&year=-1&style_id=-1&order=3&st=1&sort=0&page="
                    + page + "&season_type=1&pagesize=20&type=1";

            Document document = null;
            try {
                document = Jsoup.connect(url).timeout(3000).ignoreContentType(true).get();
            } catch (IOException e) {
                e.printStackTrace();
                System.err.println("解析url失败");
            }
            //转换为JSON
            JSONObject jsonObject = JSON.parseObject(document.text());

            List<Content> coverList = JSONObjectToCoverList(jsonObject);

            int affectedRows = mysqlService.insertContentList(coverList);

            MyBatisUtils.commit();

            System.err.println("-------第 " + page + " 页数据爬取完成");
        }

        MyBatisUtils.close();
    }


    // 把json转化为Content集合
    public static List<Content> JSONObjectToCoverList(JSONObject jsonObject) {
        List<Content> coverList = new ArrayList<>();
        JSONArray jsonArray = jsonObject.getJSONObject("data").getJSONArray("list");
        for (int i = 0; i < jsonArray.size(); i++) {
            Map<String, Object> map = (Map) jsonArray.get(i);
            Content content = new Content();
            content.setTitle(map.get("title").toString());
            content.setBadge(map.get("badge").toString());
            content.setCover(map.get("cover").toString());
            content.setIndexShow(map.get("index_show").toString());
            content.setLink(map.get("link").toString());
            content.setSeasonId(Integer.parseInt(map.get("season_id").toString()));
            content.setMediaId(Integer.parseInt(map.get("media_id").toString()));
            content.setSeasonType(Integer.parseInt(map.get("season_type").toString()));
            coverList.add(content);
        }
        return coverList;
    }
}
